import request from '@/utils/request'
import { getlistcompany } from "@/api/system/company";
import { treeDeptuser } from "@/api/system/dept";
function S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
export function uuid() {
	var id = (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	return id.replace(/-/g, "");
}

export function guuid() {
	var id = (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	return id;
}

export function findAncestry(list, id) {
	for (let i in list) {
		if (list[i].id === id) {
			//查询到就返回该数组对象
			return [list[i]]
		}
		if (list[i].children) {
			let node = findAncestry(list[i].children, id)
			if (node !== undefined) {
				//查询到把父节点连起来
				return node.concat(list[i])
			}
		}
	}
}
export function findPathByLeafId(leafId, nodes, path) {
	if (path === undefined) {
		path = {};
	}
	for (var i = 0; i < nodes.length; i++) {
		var tmpPath = path;
		if (leafId == nodes[i].id) {
			tmpPath = nodes[i];
			return tmpPath;
		}
		if (nodes[i].children) {
			var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);
			if (findResult) {
				return findResult;
			}
		}
	}
}
export function IdCodeValid(code) {
	//身份证号合法性验证
	//支持15位和18位身份证号
	//支持地址编码、出生日期、校验位验证
	var city = {
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江 ",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北 ",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏 ",
		61: "陕西",
		62: "甘肃",
		63: "青海",
		64: "宁夏",
		65: "新疆",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外 "
	};
	var row = {
		'pass': true,
		'msg': '验证成功'
	};
	if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
		row = {
			'pass': false,
			'msg': '身份证号格式错误'
		};
	} else if (!city[code.substr(0, 2)]) {
		row = {
			'pass': false,
			'msg': '身份证号地址编码错误'
		};
	} else {
		//18位身份证需要验证最后一位校验位
		if (code.length == 18) {
			code = code.split('');
			//∑(ai×Wi)(mod 11)
			//加权因子
			var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			//校验位
			var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
			var sum = 0;
			var ai = 0;
			var wi = 0;
			for (var i = 0; i < 17; i++) {
				ai = code[i];
				wi = factor[i];
				sum += ai * wi;
			}
			if (parity[sum % 11] != code[17].toUpperCase()) {
				row = {
					'pass': false,
					'msg': '身份证号校验位错误'
				};
			}
		}
	}
	return row;
}

export function analyzeIDCard(IDCard) {
	var sexAndAge = {};
	//获取用户身份证号码
	var userCard = IDCard;
	//如果身份证号码为undefind则返回空
	if (!userCard) {
		return sexAndAge;
	}
	//获取性别
	if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
		sexAndAge.sex = '1'
	} else {
		sexAndAge.sex = '2'
	}
	//获取出生年月日
	//userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
	var yearBirth = userCard.substring(6, 10);
	var monthBirth = userCard.substring(10, 12);
	var dayBirth = userCard.substring(12, 14);
	//获取当前年月日并计算年龄
	var myDate = new Date();
	var monthNow = myDate.getMonth() + 1;
	var dayNow = myDate.getDay();
	var age = myDate.getFullYear() - yearBirth;
	if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
		age--;
	}
	//得到年龄
	sexAndAge.age = age;
	//返回性别和年龄
	return sexAndAge;
}

export function getCurrentTime() {
	var nowDate = new Date().getTime(); //1564624526889
	// 调用封装好的时间转换方法
	return timestampToTime(nowDate);
}

export function timestampToTime(timestamp) {
	if (timestamp.length == 10) {
		timestamp = parseInt(timestamp) * 1000;
	}
	var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	var strDate = Y + M + D + h + m + s;
	return strDate;
}


//获取当前组织机构
export async function getcurrentcompanyid(self) {
	var companyid = self.$store.getters.selectcompanyid;
	if (companyid == null || companyid == "") {
		companyid = window.localStorage.getItem("selectcompanyid");
	}
	if (companyid == null || companyid == "") {
		//获取当前登录用户的组织机构
		companyid = self.$store.getters.companyid;
	}
	if (companyid == null || companyid == "") {
		//获取默认组织机构
		await getlistcompany(
			{ id: 1 }
		).then((response) => {
			if (response.code == 200 && response.data.length > 0) {
				companyid = response.data[0].id;
			}
		});
	}
	return companyid;
}

export async function treeDeptuserCache() {
	var list = window.localStorage.getItem("treeDeptuser");
	var currenttime = window.localStorage.getItem("deptusertime");
	if (list != null && list != undefined && list != '') {
		try {
			JSON.parse(list);
		} catch (e) {
			list = null;
		}
	}
	if (list != null && list != undefined && list != '') {
		list = JSON.parse(list);
		if (currenttime == null || currenttime == "" || currenttime == undefined) {
			currenttime = "";
		}
		await treeDeptuser({ params: { currenttime: currenttime } }).then((response) => {
			var msg = response.msg;
			if (msg == "true") {
				list = response.data;
				if (list != null && list.length > 0 && list instanceof Array) {
					window.localStorage.setItem("treeDeptuser", JSON.stringify(list));
				}
			}
			if (currenttime != response.time) {
				window.localStorage.setItem("deptusertime", response.time);
			}
		});
	} else {
		await treeDeptuser({ params: { isquery: "true" } }).then((response) => {
			list = response.data;
			if (list != null && list.length > 0 && list instanceof Array) {
				window.localStorage.setItem("treeDeptuser", JSON.stringify(list));
			}
			if (currenttime != response.time) {
				window.localStorage.setItem("deptusertime", response.time);
			}
		});
	}
	return list;
}

export function menuNavCache() {
	var value = "";
	var menu = window.localStorage.getItem("MenuNav");
	value = menu;
	if (menu == null || menu == "" || menu == undefined) {
		value = "topNav";
	}
	return value;
}

export function urlEncode(param, key, encode) {
	if (param == null) {
		return '';
	}
	var paramStr = '';
	var t = typeof (param);
	if (t == 'string' || t == 'number' || t == "boolean") {
		paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
	} else {
		for (var i in param) {
			var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
			paramStr += urlEncode(param[i], k, encode);
		}
	}
	return paramStr;
}


export function getjsonname(name) {
	var res = "";
	if (name != null && name.indexOf("[") > -1) {
		res = JSON.parse(name).toString();
	}
	return res;
}

export function getQueryParam(param) {
	var url = decodeURIComponent(location.href); //获取url中"?"符后的字串
	if (url.indexOf("?") != -1) {
		var str = url.split("?")[1];
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			var s = strs[i].split("=");
			if (s[0] == param) {
				return s[1];
			}
		}
	}
	return "";
}

/**
 * 附件上传校验
 * fileTypes: []类型，限制上传附件格式
 * file:      附件
 * maxSize:   限制文件大小，单位：MB
 */
export function isFileValid(fileTypes, file, maxSize) {
	if (fileTypes) {
		let fileExtension = "";
		if (file.name.lastIndexOf(".") > -1) {
			fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
		}
		const isTypeOk = fileTypes.some((type) => {
			if (file.type.indexOf(type) > -1) return true;
			if (fileExtension && fileExtension.indexOf(type) > -1) return true;
			return false;
		});
		if (!isTypeOk) {
			return -1;
		}
	}
	// 校检文件大小
	if (maxSize) {
		const isLt = file.size / 1024 / 1024 < maxSize;
		if (!isLt) {
			return 0;
		}
	}
	return 1;
}


export function getclientWidth() {
	(function (doc, win) {
		var docEI = doc.documentElement;
		docEI.style.fontSize = 14 * (docEI.clientWidth / 1920) + 'px';
		var resizeEvt = 'orientationchange' in window ? 'orientataionchange' : 'resize',
			recalc = function () {
				var clientWidth = docEI.clientWidth;
				if (!clientWidth) return;
				//14是字体大小，1920是开发时浏览器窗口的宽度，等比计算
				docEI.style.fontSize = 14 * (clientWidth / 1920) + 'px';
			}

		if (!doc.addEventListener) return;
		win.addEventListener(resizeEvt, recalc, false);
		doc.addEventListener('DOMContentLoaded', recalc, false);
	})(document, window);
}

export function getstr(text, value) {
	var str = "";
	if (text != null && text != '' && text != undefined) {
		str = text;
	}
	if (value != null && value != '' && value != undefined) {
		if (str == "") {
			str = value;
		} else {
			str = str + ";" + value;
		}
	}
	return str;
}

const addimg = require('@/assets/image/add_btn_icon2.png');
const editimg = require('@/assets/image/edit_btn_icon2.png');
const viewimg = require('@/assets/image/view_btn_icon2.png');

export function dialogIcon(type) {
	var id = "";
	var hidden = "";
	var dialogs = $(".el-dialog");
	for (var i = 0; i < dialogs.length; i++) {
		id = $(dialogs[i]).attr("id");
		hidden = $(dialogs[i]).parent().is(":hidden");
		if (id == null || id == "" || id == undefined) {
			$(dialogs[i]).attr("id", guuid());
		}
		if (hidden == false) {
			id = $(dialogs[i]).attr("id");
		}
	}

	$(".el-dialog[id='" + id + "'] .dialog-item-btn").remove();
	$(".el-dialog[id='" + id + "'] .hr-dotted").remove();
	if (type == "add") {
		$(".el-dialog[id='" + id + "'] .el-dialog__header .el-dialog__title").before("<img src='" + addimg + "' class='dialog-item-btn dialog-add-btn'>");
		$(".el-dialog[id='" + id + "'] .el-dialog__body").before("<hr class='hr-dotted' />");
	} else if (type == "edit") {
		$(".el-dialog[id='" + id + "'] .el-dialog__header .el-dialog__title").before("<img src='" + editimg + "' class='dialog-item-btn dialog-edit-btn'>");
		$(".el-dialog[id='" + id + "'] .el-dialog__body").before("<hr class='hr-dotted' />");
	} else if (type == "view") {
		$(".el-dialog[id='" + id + "'] .el-dialog__header .el-dialog__title").before("<img src='" + viewimg + "' class='dialog-item-btn dialog-view-btn'>");
		$(".el-dialog[id='" + id + "'] .el-dialog__body").before("<hr class='hr-dotted' />");
	}
}

export function getmappointurl() {
  return "http://124.88.56.22:8834/single.html";
}